import { ref, computed, watch } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useAdminStore } from '../stores/admin'
import { useToast } from 'vue-toastification'
import { PermissionUtils } from '../utils/permissions'
import type { Router } from 'vue-router'

// 全局状态管理
export function useGlobalState(router?: Router) {
  const authStore = useAuthStore()
  const adminStore = useAdminStore()
  const toast = useToast()

  // 应用状态
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const isOnline = ref(navigator.onLine)

  // 计算属性
  const currentUser = computed(() => authStore.user)
  const isAuthenticated = computed(() => authStore.isAuthenticated)
  const userPermissions = computed(() => {
    if (!currentUser.value) return {}
    
    return {
      canCreateUser: PermissionUtils.canPerformAction(currentUser.value, 'create_user'),
      canCreateSubAdmin: PermissionUtils.canPerformAction(currentUser.value, 'create_sub_admin'),
      canViewAdminPanel: PermissionUtils.canPerformAction(currentUser.value, 'view_admin_panel'),
      canViewSystemStats: PermissionUtils.canPerformAction(currentUser.value, 'view_system_stats'),
      canManageSubAdmins: PermissionUtils.canPerformAction(currentUser.value, 'manage_sub_admins'),
      canAccessUserManagement: PermissionUtils.canAccessModule(currentUser.value, 'user_management'),
      canAccessSubAdminManagement: PermissionUtils.canAccessModule(currentUser.value, 'sub_admin_management'),
      canAccessSystemSettings: PermissionUtils.canAccessModule(currentUser.value, 'system_settings'),
      canAccessAuditLogs: PermissionUtils.canAccessModule(currentUser.value, 'audit_logs'),
      canAccessRechargeManagement: PermissionUtils.canAccessModule(currentUser.value, 'recharge_management'),
      canAccessPayoutManagement: PermissionUtils.canAccessModule(currentUser.value, 'payout_management'),
    }
  })

  const accessibleMenuItems = computed(() => {
    return PermissionUtils.getAccessibleMenuItems(currentUser.value)
  })

  // 网络状态监听
  function setupNetworkListeners() {
    window.addEventListener('online', () => {
      isOnline.value = true
      toast.success('Connection restored')
    })

    window.addEventListener('offline', () => {
      isOnline.value = false
      toast.warning('Connection lost')
    })
  }

  // 用户状态监听
  watch(
    () => authStore.user,
    (newUser, oldUser) => {
      // 用户登录
      if (newUser && !oldUser) {
        console.log('User logged in:', newUser.email)
        
        // 检查当前路由是否需要认证，避免在公开页面加载管理员数据
        const currentRoute = router?.currentRoute.value
        const isPublicRoute = currentRoute?.meta?.requiresAuth === false
        const isUserRechargePage = currentRoute?.name === 'UserRecharge'
        
        // 只在认证页面且是管理员时才预加载数据，特别排除用户充值页面
        if (PermissionUtils.hasAdminAccess(newUser) && 
            !isPublicRoute && 
            !isUserRechargePage &&
            currentRoute?.meta?.requiresAuth !== false) {
          // 延迟执行，确保路由完全加载
          setTimeout(() => {
            try {
              adminStore.getSystemStats().catch((error) => {
                console.warn('Admin stats loading failed:', error)
              })
            } catch (error) {
              console.warn('Admin stats execution failed:', error)
            }
          }, 100)
        }
      }
      
      // 用户登出
      if (!newUser && oldUser) {
        console.log('User logged out')
        
        // 清理管理员状态
        adminStore.resetState()
        
        // 重定向到登录页
        if (router && router.currentRoute.value.name !== 'Login') {
          router.push('/login')
        }
      }
      
      // 用户角色变更
      if (newUser && oldUser && newUser.role !== oldUser.role) {
        console.log('User role changed:', oldUser.role, '->', newUser.role)
        toast.info(`Your role has been updated to ${PermissionUtils.getRoleDisplayName(newUser.role)}`)
        
        // 如果失去管理员权限，重定向到仪表板
        if (PermissionUtils.hasAdminAccess(oldUser) && !PermissionUtils.hasAdminAccess(newUser)) {
          if (router && router.currentRoute.value.name === 'Admin') {
            router.push('/dashboard')
          }
        }
      }
      
      // 用户被停用
      if (newUser && oldUser && newUser.isActive !== oldUser.isActive && !newUser.isActive) {
        toast.error('Your account has been deactivated')
        authStore.logout()
      }
    },
    { deep: true }
  )

  // 路由变化监听
  if (router) {
    watch(
      () => router.currentRoute.value,
      (to, from) => {
        // 清除错误状态
        error.value = null

        // 记录页面访问
        console.log(`Navigation: ${String(from?.name) || 'unknown'} -> ${String(to.name) || 'unknown'}`)

        // 检查权限
        if (to.meta.requiresAuth && currentUser.value) {
          // 检查路由权限
          if (!PermissionUtils.canAccessRoute(currentUser.value, to.name?.toString() || '')) {
            toast.error('您没有权限访问此页面')
            router.push('/dashboard')
            return
          }

          // 检查管理员权限
          if (to.meta.requiresAdmin && !PermissionUtils.hasAdminAccess(currentUser.value)) {
            toast.error('需要管理员权限')
            router.push('/dashboard')
            return
          }

          // 检查模块权限
          if (to.meta.requiresModule && !PermissionUtils.canAccessModule(currentUser.value, to.meta.requiresModule)) {
            toast.error('您没有权限访问此功能模块')
            router.push('/dashboard')
            return
          }
        }
      }
    )
  }

  // 全局错误处理
  function handleGlobalError(err: Error | string, context?: string) {
    const errorMessage = typeof err === 'string' ? err : err.message
    error.value = errorMessage
    
    console.error(`Global error${context ? ` in ${context}` : ''}:`, err)
    
    // 根据错误类型显示不同的提示
    if (errorMessage.includes('UNAUTHORIZED') || errorMessage.includes('401')) {
      toast.error('Session expired. Please login again.')
      authStore.logout()
    } else if (errorMessage.includes('FORBIDDEN') || errorMessage.includes('403')) {
      toast.error('You do not have permission to perform this action')
    } else if (errorMessage.includes('Network') || errorMessage.includes('fetch')) {
      toast.error('Network error. Please check your connection.')
    } else {
      toast.error(errorMessage)
    }
  }

  // 清除错误
  function clearError() {
    error.value = null
  }

  // 检查用户权限
  function checkPermission(action: string, targetUser?: any): boolean {
    return PermissionUtils.canPerformAction(currentUser.value, action, targetUser)
  }

  // 检查模块访问权限
  function checkModuleAccess(module: string): boolean {
    return PermissionUtils.canAccessModule(currentUser.value, module)
  }

  // 安全导航
  function navigateWithPermissionCheck(routeName: string, params?: any) {
    if (!router) {
      console.warn('Router not available for navigation')
      return
    }

    if (!currentUser.value) {
      router.push('/login')
      return
    }

    if (!PermissionUtils.canAccessRoute(currentUser.value, routeName)) {
      toast.error('You do not have permission to access this page')
      return
    }

    router.push({ name: routeName, params })
  }

  // 初始化
  function initialize() {
    setupNetworkListeners()
    
    // 恢复用户状态
    authStore.initAuth()
    
    // 检查当前路由是否需要认证，避免在公开页面加载管理员数据
    const currentRoute = router?.currentRoute.value
    const isPublicRoute = currentRoute?.meta?.requiresAuth === false
    const isUserRechargePage = currentRoute?.name === 'UserRecharge'
    
    // 只在认证页面且用户已登录且是管理员时才预加载数据
    // 特别排除用户充值页面
    if (isAuthenticated.value && 
        PermissionUtils.hasAdminAccess(currentUser.value) && 
        !isPublicRoute && 
        !isUserRechargePage &&
        currentRoute?.meta?.requiresAuth !== false) {
      // 延迟执行，确保路由完全加载
      setTimeout(() => {
        try {
          adminStore.getSystemStats().catch((error) => {
            console.warn('Admin stats loading failed:', error)
          })
        } catch (error) {
          console.warn('Admin stats execution failed:', error)
        }
      }, 100)
    }
  }

  return {
    // 状态
    isLoading,
    error,
    isOnline,
    currentUser,
    isAuthenticated,
    userPermissions,
    accessibleMenuItems,
    
    // 方法
    handleGlobalError,
    clearError,
    checkPermission,
    checkModuleAccess,
    navigateWithPermissionCheck,
    initialize,
  }
}

// 创建全局实例
let globalStateInstance: ReturnType<typeof useGlobalState> | null = null

export function createGlobalState(router?: Router) {
  if (!globalStateInstance) {
    globalStateInstance = useGlobalState(router)
    globalStateInstance.initialize()
  }
  return globalStateInstance
}

export function getGlobalState() {
  if (!globalStateInstance) {
    throw new Error('Global state not initialized. Call createGlobalState() first.')
  }
  return globalStateInstance
}
